package com.devMode.ChainOfResponsibility;

/**
 * 行为链模式
 * 使得多个对象都可以处理请求，从而避免请求发送者和接收者之间发生耦合
 * 将这些对象组织成一条链，并且沿着这条链发送该请求，直到有一个对象处理为止
 */
public class ChainOfRespinsibilityMode {
    public static void main(String[] args) {
        Handler handler1 = new ConcreateHandler1(null);
        Handler handler2 = new ConcreateHandler2(handler1);

        Request request1 = new Request(RequstType.TYPE1,"request1");
        handler1.handleRequest(request1);

        Request request2 = new Request(RequstType.TYPE1,"request2");
        handler2.handleRequest(request2);
    }
}

abstract class Handler{
    //下一步要处理的那个处理器
   protected Handler successor;

   public Handler(Handler successor){
       this.successor = successor;
   }

   protected abstract void handleRequest(Request request);
}

class ConcreateHandler1 extends  Handler{

    public ConcreateHandler1(Handler successor){
        super(successor);
    }

    @Override
    protected void handleRequest(Request request) {
        if(request.getRequstType() == RequstType.TYPE1){
            System.out.println(request.getName() + " is handle by concreatehandler1");
        }
        if(successor!=null)
            successor.handleRequest(request);
    }
}


class ConcreateHandler2 extends  Handler{

    public ConcreateHandler2(Handler successor){
        super(successor);
    }

    @Override
    protected void handleRequest(Request request) {
        if(request.getRequstType() == RequstType.TYPE1){
            System.out.println(request.getName() + " is handle by concreatehandler2");
        }
        if(successor!=null)
            successor.handleRequest(request);
    }
}

class Request {
    private RequstType requstType;
    private String name;

    public Request(RequstType requstType, String name){
        this.requstType = requstType;
        this.name = name;
    }

    public RequstType getRequstType(){
        return this.requstType;
    }

    public String getName(){
        return this.name;
    }

}

enum RequstType{
    TYPE1,TYPE2
}
